

import commonutils as common
from appmanager import AppManager
from appmanager import Mode
import os
import urlresolver
import ast
import math

class AmharicMovies:

    _main_url = ''
    _name = 'AmharicMovies'
    _icon_path = str(os.path.dirname(os.path.realpath(__file__))) + '/../icons/amharicmovies/'
    _fanart_path = str(os.path.dirname(os.path.realpath(__file__))) + '/../fanarts/amharicmovies/'
   
    def __init__(self,app_manager):
       _main_url = 'http://www.amharicmovies.com/'
       self.app = app_manager
       
    def getName(self):
        return AmharicMovies._name
    
    def getIcon(self):
        return AmharicMovies._icon_path + 'main.png'
    
    def getNextPageIcon(self):
        return AmharicMovies._icon_path + 'nextpage.png'
       
    def getFanart(self):
        return AmharicMovies._fanart_path + 'main.jpg'
    
    def getCategoryFanart(self):
        return AmharicMovies._fanart_path + 'categoryfanart.jpg'
    
    def getSubMenuFanart(self):
        return AmharicMovies._fanart_path + 'submenufanart.jpg'
        

    def displayMainMenu(self):
        import time
        start = time.clock()

        print 'getting category'
        match = self.getCategoryList()
        print '-----reading url took '
        print time.clock() - start
        for eachmatch in match:
            category = eachmatch[0]
            sub_category = eachmatch[1]
            self.app.getAddon().add_directory({'mode': Mode.SUBMENUSELECTED, 'name': self.getName(), 'category': category, 'subcategory': sub_category}, {'title': category}, img='newtv.png')

    def displaySubMenu(self):
        sub_category_str = self.app.getAddonQueries('subcategory')
        if not sub_category_str == None:
            sub_category = ast.literal_eval(sub_category_str)
            for item in sub_category:
                link = item[0]
                category = item[1]
                self.app.getAddon().add_directory({'mode': Mode.SUBMENUSELECTED, 'name': self.getName(), 'url': link, 'category': category}, {'title': category}, img='newtv.png')
            
        else:
            page_url = self.app.getURL()
            if not page_url.startswith('http://www.amharicmovies.com/'):
                page_url = 'http://www.amharicmovies.com/' + page_url        
            total_pages = self.populateMediaList(page_url)
            title = '1 of ' + str(total_pages)+ ' Next Page >>>' if int(total_pages) > 1 else '1 of ' + str(total_pages)
            self.app.getAddon().add_directory({'mode': Mode.NEXT, 'name': self.getName(), 'url': page_url, 'page_num': 1, 'total_pages': total_pages}, {'title': title}, img=self.getNextPageIcon())
        
      
    def displayNextPage(self):
        page_num = self.app.getAddonQueries('page_num')
        cur_page = int(page_num) + 1
        url = self.app.getURL()
        page_url = url[:-6] + str(cur_page) + '.html'
        print 'page url is -----------'
        print page_url
        self.populateMediaList(page_url)
        total_pages = self.app.getAddonQueries('total_pages')
        if int(cur_page) < int(total_pages):
            self.app.getAddon().add_directory({'mode': Mode.NEXT, 'name': self.getName(), 'url': page_url, 'page_num': cur_page, 'total_pages': total_pages}, {'title': str(cur_page) + ' of ' + str(total_pages)+ ' Next Page >>>'}, img=self.getNextPageIcon())
       

    def getBrowseListForPage(self, pageUrl):
        start = '<div id=\"content-loop\">'
        end = '<div class="advert" align="center">'
        page_src = common.urlReader(pageUrl)
        #print (page_src)
        browse_result = common.extractSubString(page_src,start,end)
        #print (browse_result)
        match = common.find('<a class=\"clip-link\"\s*.*\s*title="(.+?)"\s*href="(.+?)">\s*<span class="clip">\s*.*\s*src="(.+?)"\s*.*\s*</span>', browse_result)
        page_num_info = common.find('</span>\s*total:\s*.*\s*(\d*)\s*.*\s*.*\s*.*\s*(\d*\s*-\s*\d*)\s*</span>',browse_result)
        print page_num_info
        total_pages = 1
        for info in page_num_info:
            total_item = int(info[0])
            cur_dis = info[1].replace(" ", "").split('-')
            total_pages = total_item / float(cur_dis[-1])
            total_pages = math.ceil(total_pages)
            print total_pages
        return (total_pages,match)
    
    def populateMediaList(self,page_url):
        res = self.getBrowseListForPage(page_url)
        total_pages = int(res[0])
        match = res[1]
        print res
        for eachmatch in match:
            title = eachmatch[0]
            link = eachmatch[1]
            head, sep, tail = eachmatch[2].partition('amp;')
            icon = head + tail
            print link.startswith('http://www.amharicmovies.com/')
            if link.startswith('http://www.amharicmovies.com/') == False:
                link = 'http://www.amharicmovies.com/' + str(link) 
            print link              
            videoPage = common.urlReader(link)
            matchLink = common.find('file:\s*\'(.+?)\'', videoPage)
            if len(matchLink) < 1:
                log = 'the empty link is(((********' + link
                print log
            print 'matchLink'
            print matchLink
            if len(matchLink) > 0 :
                videoLink = matchLink[0]
                print 'videoLink ---- is'
                print videoLink
                d = 22 - len(videoLink)
                if 'http://www.youtube.com' == videoLink[:d]:
                    media = urlresolver.HostedMediaFile(videoLink)
                    videoLink = media.resolve()
                    print videoLink
                try:
                    print title
                except UnicodeEncodeError as detail:
                    title = common.removeNonASCII(title)
                self.app.getAddon().add_video_item({'mode': Mode.PLAY, 'url': videoLink}, {'title': title}, img=icon,)
        return total_pages
   
    def getCategory(self,url):
        print(url)
        main_src = common.urlReader(url)
        start_str1 = '<a href=\"videos/index.1.html\">'
        end_str1 = '<a href=\"photos/index.1.html\">'
        start_str2 = '<a href="tv-shows/index.1.html">'
        end_str2 = '<a href="ethiopian-cuisine/index.1.html">'
        vid_mov_music = common.extractSubString(main_src, start_str1, end_str1)
        tv_shows = common.extractSubString(main_src, start_str2, end_str2)
        a_m_category = vid_mov_music + tv_shows
        #print(vid_mov_music)
        return common.find('<a href="(.+?)">\s*(.+?)\s*</a>',a_m_category)


    def getCategoryList(self):
        unsorted_category = self.getCategory('http://www.amharicmovies.com/')
        category_list = []
        item_list = []
        key = ''
        is_index = False
        appending = False
        for item in unsorted_category:
            link = str(item[0])
            name = str(item[1])
            if not link.startswith('http'):
                is_index = link[link.find('/') :] == '/index.1.html'
                if is_index:
                    if appending:
                        category_list.append((key,item_list[:]))
                        del item_list[:]
                    print (len(item_list))
                    key = name
                    is_index = False
                    appending = True
                    continue
            item_list.append(item)
        category_list.append((key,item_list[:]))         
        return category_list